package com.tengfei.main;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author feige
 * @version v1.0
 * @date 2022-09-21-9:50
 * @description jdk动态代理
 */
public class JavaDynamicProxy {

    public static void main(String[] args) {
        Service service = (Service) JdkProxyFactory.getProxy(new ServiceImpl());
        service.send("发送短信哈...");
    }
}

// 代理类型
class JdkInvokeHandler implements InvocationHandler {

    private final Object service;

    // 构造器注入
    JdkInvokeHandler(Object service) {
        this.service = service;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("代理运行前：" + method.getName());
        Object res = method.invoke(service, args);
        System.out.println("代理运行后：" + method.getName());
        return res;
    }
}


// 代理工厂
class JdkProxyFactory {
    public static Object getProxy(Object target) {
        return Proxy.newProxyInstance(
                // 被代理类的类加载器
                target.getClass().getClassLoader(),
                // 被代理类的需要实现的接口
                target.getClass().getInterfaces(),
                // 代理对象
                new JdkInvokeHandler(target)
        );
    }
}

